from app import ma
from .models import Category

# 分类序列化模式
class CategorySchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Category
        load_instance = True
        # 让Marshmallow自动发现所有字段，避免版本兼容性问题
    
    # 【关键修复】使用类名直接引用实现自引用，不使用exclude参数
    children = ma.Nested('CategorySchema', many=True)

# 创建单分类和多分类的序列化器实例
category_schema = CategorySchema()
categories_schema = CategorySchema(many=True)

# 简化版分类序列化模式（不包含子分类）
class CategorySimpleSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Category
        load_instance = True
        exclude = ('parent', 'children')  # 排除关系字段，只保留基础字段

category_simple_schema = CategorySimpleSchema()
categories_simple_schema = CategorySimpleSchema(many=True)